import datetime
import logging
from django.http import HttpResponse
import xlwt
from xlwt.Formatting import Font
from xlwt.Style import XFStyle
from jrcmodel.models import CST, Market, Asset
from src.pet.models import EuroConvDaily
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from tracking.models import TrackRecordFutures, TrackRecordForex

@login_required
def index(request):
    now = datetime.datetime.now()
    return render_to_response(
        "xport/index.html"
        , {
            "years": range(2010, now.year + 1)
            , "months": range(1, 13)
        }
        , context_instance = RequestContext(request)
    )

@login_required
def cst(request, pk):
    """
        Exports CST to XLS file by its PK and forces to download it
    """
    cst = CST.objects.get(pk = pk)

    wb = xlwt.Workbook()
    ws = wb.add_sheet("CST %s" % cst.name)

    # Create style to format date
    date_style = XFStyle()
    date_style.num_format_str = "M/D/YY"

    # Style for header
    label_style = XFStyle()
    label_style.font = Font()
    label_style.font.bold = True

#    ws.col(1).width = 200
#    ws.col(4).width = 200

    row = 5
    ws.write(row, 1, cst.market_direction_1.__unicode__())
    if cst.market_direction_2:
        ws.write(row, 4, cst.market_direction_2.__unicode__())
    row += 2

    # Get data about CST markets
    market1 = cst.market_direction_1.market_id
    if cst.market_direction_2:
        market2 = cst.market_direction_2.market_id
    else:
        market2 = None

    ws.write(row, 1, "Status", label_style)
    ws.write(row, 4, "Status", label_style)
    ws.write(row, 2, market1.status_name())
    if market2:
        ws.write(row, 5, market2.status_name())
    row += 1
    ws.write(row, 1, "Asset class", label_style)
    ws.write(row, 4, "Asset class", label_style)
    ws.write(row, 2, market1.asset.__unicode__())
    if market2:
        ws.write(row, 5, market2.asset.__unicode__())
    row += 1
    ws.write(row, 1, "Name", label_style)
    ws.write(row, 4, "Name", label_style)
    ws.write(row, 2, market1.name)
    if market2:
        ws.write(row, 5, market2.name)
    row += 1
    ws.write(row, 1, "Currency", label_style)
    ws.write(row, 4, "Currency", label_style)
    ws.write(row, 2, market1.currency_code)
    if market2:
        ws.write(row, 5, market2.currency_code)
    row += 1
    ws.write(row, 1, "Points", label_style)
    ws.write(row, 4, "Points", label_style)
    ws.write(row, 2, market1.get_points_fmt())
    if market2:
        ws.write(row, 5, market2.get_points_fmt())
    row += 1
    ws.write(row, 1, "Point price", label_style)
    ws.write(row, 4, "Point price", label_style)
    ws.write(row, 2, market1.point_price)
    if market2:
        ws.write(row, 5, market2.point_price)
    row += 1
    ws.write(row, 1, "Price of points", label_style)
    ws.write(row, 4, "Price of points", label_style)
    ws.write(row, 2, market1.get_price_of_points())
    if market2:
        ws.write(row, 5, market2.get_price_of_points())
    row += 1
    ws.write(row, 1, "Start", label_style)
    ws.write(row, 4, "Start", label_style)
    ws.write(row, 2, market1.start, date_style)
    if market2:
        ws.write(row, 5, market2.start, date_style)
    row += 1
    ws.write(row, 1, "End", label_style)
    ws.write(row, 4, "End", label_style)
    ws.write(row, 2, market1.end, date_style)
    if market2:
        ws.write(row, 5, market2.end, date_style)
    row += 1

    row += 10
    ws.write(row, 1, "Cash or Future")
#    ws.write(row, 2, cst.market_direction_1.cash_or_future_name)
    ws.write(row, 4, "Cash or Future")
#    ws.write(row, 5, cst.market_direction_2.cash_or_future_name)


    response = HttpResponse(content_type = "application/ms-excel")
    response["Content-Disposition"] = "attachment; filename=CST-%s.xls" % cst.name.replace(' ', '_')
    wb.save(response)
    return response

@login_required
def trackrecords(request):
    # @var TrackRecordFutures tr
    log = logging.getLogger("ittc")
    now = datetime.datetime.now()
    year = int(request.GET.get("year", now.year))
    month = int(request.GET.get("month", now.month))
    log.info("Exporting Track records for %d-%d" % (year, month))

    # Name for downloadable excel file
    export_file = "%d-%d Track record.xls" % (year, month)

    wb = xlwt.Workbook()
    ws = wb.add_sheet("Futures")

    decimal_fmt = XFStyle()
    decimal_fmt.num_format_str = "0.0####"
    date_fmt = XFStyle()
    date_fmt.num_format_str = "M/D/YY"
    header_fmt = XFStyle()
    header_fmt.font = Font()
    header_fmt.font.bold = True

    # Create labels for Futures
    labels = [u"Date", u"Market", u"#Contacts", u"Dir.", u"Entry", u"Exit"]
    for col in range(0, len(labels)):
        ws.write(0, col, labels[col], header_fmt)

    futures = TrackRecordFutures.get_tracks_by_month(year, month)
    log.info("Got %d Track records (Futures)" % len(futures))
    row = 1

    # Write Futures to worksheet
    for tr in futures:
        ws.write(row, 0, tr.date, date_fmt)
        ws.write(row, 1, tr.get_market().name)
        ws.write(row, 2, tr.contracts_qnt)
        ws.write(row, 3, tr.direction_name())
        ws.write(row, 4, tr.entry_value, decimal_fmt)
        ws.write(row, 5, tr.exit_value, decimal_fmt)
        row += 1


    ws = wb.add_sheet("Forex")

    # Create labels for Forex
    labels = [u"Date", u"Market", u"Fee", u"Min mov.", u"Dir.", u"Entry", u"Exit"]
    for col in range(0, len(labels)):
        ws.write(0, col, labels[col], header_fmt)

    forex = TrackRecordForex.get_tracks_by_month(year, month)
    log.info("Got %d Track records (Forex)" % len(forex))
    row = 1

    # Write Forex to worksheet
    for tr in forex:
        ws.write(row, 0, tr.date, date_fmt)
        ws.write(row, 1, tr.get_market().name)
        ws.write(row, 2, tr.get_min_mov(), decimal_fmt)
        ws.write(row, 3, tr.direction_name())
        ws.write(row, 4, tr.entry_value, decimal_fmt)
        ws.write(row, 5, tr.exit_value, decimal_fmt)
        row += 1

    ws = wb.add_sheet("EUR conversion")

    # Create header for EUR conversion
    labels = ["Date", "EURUSD", "EURJPY", "EURGBP", "EURCHF", "EURAUD", "EURNZD", "EURCAD"]
    for col in range(0, len(labels)):
        ws.write(0, col, labels[col], header_fmt)

    month_len = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0]
    date_from = "%d-%d-01" % (year, month)
    date_to = "%d-%d-%d" % (year, month, month_len[month])
    euros = EuroConvDaily.objects.all().filter(date__gte = date_from).filter(date__lte = date_to)
    log.info("Got %d EUR conversions in [%s - %s]" % (len(euros), date_from, date_to))

    row = 1
    for euro in euros:
        ws.write(row, 0, euro.date, date_fmt)
        ws.write(row, 1, euro.EURUSD, decimal_fmt)
        ws.write(row, 2, euro.EURJPY, decimal_fmt)
        ws.write(row, 3, euro.EURGBP, decimal_fmt)
        ws.write(row, 4, euro.EURCHF, decimal_fmt)
        ws.write(row, 5, euro.EURAUD, decimal_fmt)
        ws.write(row, 6, euro.EURNZD, decimal_fmt)
        ws.write(row, 7, euro.EURCAD, decimal_fmt)
        row += 1

    response = HttpResponse(mimetype = "application/ms-excel")
    response["Content-Disposition"] = "attachment; filename=%s" % export_file
    wb.save(response)
#    wb.save(os.path.join(MEDIA_ROOT, "testtracks.xls"))

#    return HttpResponse("Done...")
    return response


